package com.cutefool.zero.code.admin.meta.column.rules.invoker;

import com.cutefool.commons.redis.SerialRedisGenerator;
import com.cutefool.core.kits.jackson.Jackson;
import com.cutefool.core.kits.spring.SpiSpringContext;
import com.cutefool.core.kits.util.Strings;
import com.cutefool.core.kits.util.Times;
import com.cutefool.zero.code.admin.meta.column.dto.SerialOption;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

public class AutoSerialInvoker implements SerialInvoker {

    public String invoke(String model, SerialOption serialOption) {
        String rule = serialOption.getRule();
        Optional<Item> optional = Jackson.toBean(rule, Item.class);
        if (optional.isEmpty()) {
            return Strings.EMPTY;
        }
        // 表达时间表达
        Item item = optional.get();
        String express = item.getExpress();
        Integer init = item.getInit();
        // redis数据库主键
        String key = model + (StringUtils.isNotBlank(express) ? Times.format(LocalDateTime.now(), express) : express);
        SerialRedisGenerator serialRedisGenerator = SpiSpringContext.getOneSpi(SerialRedisGenerator.class);
        if (Objects.nonNull(serialRedisGenerator)) {
            serialRedisGenerator.generate("", key, String.valueOf(Objects.isNull(init) ? 1 : init), item.getLen(), null);
        }
        return Strings.EMPTY;
    }

    @Data
    static final class Item {
        /**
         * 初始值
         */
        private Integer init;

        /**
         * 位数
         */
        private Integer len;

        /**
         * 规则
         */
        private String express;

    }
}
